package hanshunping.project.chatRoom.chatServer.server.service;

import hanshunping.project.chatRoom.common.Message;
import hanshunping.project.chatRoom.common.MessageType;
import hanshunping.project.chatRoom.common.User;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ConcurrentHashMap;

/**
 * create by: 蔡博
 * description: TODO
 * create time: 2022/11/17 11:19
 * 这是服务器，在监听9999，等待客户端连接，并保持通信
  * @Param: null
 * @return
 */
public class ChatServer {
    private ServerSocket ss;
    private static ConcurrentHashMap<String,String> users = new ConcurrentHashMap();
    static {
        users.put("trueno","123456");
        users.put("jack","8436579");
        users.put("rufus","1");
        users.put("nate","1");
    }
    boolean check(User user){
        boolean res = false;
        if(users.get(user.getUserId())!=null&&users.get(user.getUserId()).equals(user.getPasswd()))
            res = true;
        return res;
    }
    public ChatServer(){
        try {
            System.out.println("服务器在9999端口监听");
            ss = new ServerSocket(9999);
            Socket socket;
            while(true){
                socket = ss.accept();
                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                User u = (User) ois.readObject();
                ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                Message mes = new Message();
                if(check(u)){
                    System.out.println(u.getUserId()+"=====登录");
                    mes.setMesType(MessageType.MESSAGE_LOGIN_SUCCEED);
                    oos.writeObject(mes);
                    ConnectThread ct = new ConnectThread(socket,u.getUserId());
                    ct.start();
                    ManageConnectThread.addThread(u.getUserId(),ct);
                }else{
                    mes.setMesType(MessageType.MESSAGE_LOGIN_FAIL);
                    oos.writeObject(mes);
                    socket.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                ss.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
